package com.woniu108.carService.commos.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 文件上传OSS工具类
 *
 * @author Administrator
 */
@ConfigurationProperties(prefix = "aliyun.oss")
@Component
@Data
public class OSSUtil {

    /**
     * 节点域名
     */
    private String host;
    /**
     * 账号的身份ID
     */
    private String accessId;

    /**
     * 账号的身份凭证
     */


    private String accessSecret;

    /**
     * 上传文件
     *
     * @param file       文件数据
     * @param name       文件名
     * @param bucketName 存储空间名
     * @return 文件的访问地址
     */
    public String uploadFile(InputStream file, String name, String bucketName) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://" + host, accessId, accessSecret);
        try {
            //上传
            ossClient.putObject(bucketName, name, file);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://" + bucketName + "." + host + "/" + name;
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储空间名
     * @param name       文件名
     * @return boolean值
     */
    public boolean deleteFile(String bucketName, String name) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://" + host, accessId, accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, name);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return true;
    }

}


